//
//  RecordVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/12/14.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "RecordVC.h"
#import "TopBackView.h"
#import "RecordCell.h"
#import "RootViewController.h"
#import "WKProgressHUD.h"
#import "NullView.h"
#import "Common.h"
#import <MJRefresh.h>//下拉刷新
#import "RLNetworkHelper.h"//网络判断



@interface RecordVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) NSMutableDictionary *dic;

@property (nonatomic,strong) UIView *netView;

@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;
@property (nonatomic) int pageNo;
@property (nonatomic) NSInteger pageTotal;
@end

@implementation RecordVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"个人中心"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:topBackView];
    self.dataArray = [NSMutableArray array];
    self.dic = [NSMutableDictionary dictionary];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    self.pageNo = 1;

//    [self initSourceData];
    
    [self initTableView];
}

-(void)initSourceData
{
    NSString *urlString = [NSString stringWithFormat:@"%@billdetail/monthdetails?pageNo=%d&pageSize=10",Main_interface,self.pageNo];
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss: YES];
        
        if (self.pageNo == 1) {
            
            [self.dataArray removeAllObjects];
            
        }
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        
        if ([responseObj[@"success"] boolValue]) {
            
            [self.hud dismiss:YES];
            
            NSMutableSet *set = [NSMutableSet set];
            
            for (NSDictionary *dic in responseObj[@"data"][@"details"]) {
                
                set = [NSMutableSet setWithObject:dic[@"monthText"]];

                [self.dataArray addObject:dic];
            }
            
            NSArray *arr = [set allObjects];
            
            for (int i = 0; i < arr.count ; i++) {
                NSMutableArray *arrS = [NSMutableArray array];
                for (int j = 0; j <  [responseObj[@"data"][@"details"] count] ; j++) {
                    
                    if ( [ responseObj[@"data"][@"details"][j][@"monthText"] isEqualToString:arr[i] ])
                        
                    {
                        [arrS addObject:responseObj[@"data"][@"details"][j]];
                    }
                    
                    [self.dic setObject:arrS forKey:arr[i]];
                    
                }

            }
            
            if (self.dataArray.count > 0) {
                [self.nullView removeFromSuperview];
            } else {
                [self.tableView addSubview:self.nullView];
            }
        }
        
        
        [self.tableView reloadData];
        
        
    } failed:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];

}

-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
        
    }
    else{
        [self.netView removeFromSuperview];
        [self initSourceData];
    }
}
//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initSourceData];
    } else {
        [self.hud dismiss:YES];
    }
}

-(void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    
    [self judgeNetWork];
}
-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}

    -(void)initTableView
    {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth,screenHeight) style:UITableViewStyleGrouped];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableFooterView = [[UIView alloc]init];
        [self.view addSubview:self.tableView];
        
        
        //mj
        [self.tableView.mj_header beginRefreshing];
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
        
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
        
        //无网络状态
        [self createNetWorkAndStatue];
    }
    
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        
        NSArray *arr = [self.dic allKeys];
        return arr.count;
    }
    
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        NSArray *arr = [self.dic allKeys];
        
        
        return [[self.dic objectForKey:arr[section]] count];
        
    }
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *string = @"testCell";
        RecordCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[RecordCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSArray *arr = [self.dic allKeys];
        NSArray *arr1 = [self.dic objectForKey:arr[indexPath.section]];
        if (arr.count > 0) {
            
            
            NSString *string = arr1[indexPath.row][@"createTime"];
            NSArray *arr = [string componentsSeparatedByString:@" "];
            
            cell.timeLabel.text = arr[0];
            cell.addressLabel.text = [NSString stringWithFormat:@"%@--%@",arr1[indexPath.row][@"departAddr"],arr1[indexPath.row][@"arrivalAddr"]];
            
            cell.priceLabel.text = arr1[indexPath.row][@"orderActPayText"] ;
            
            [cell showValue:arr1[indexPath.row][@"priceVo"] ];
            
        }
        
//        if (self.dataArray.count > 0) {
//        
//            NSString *string = self.dataArray[indexPath.row][@"createTime"];
//            NSArray *arr = [string componentsSeparatedByString:@" "];
//            
//            cell.timeLabel.text = arr[0];
//            cell.addressLabel.text = [NSString stringWithFormat:@"%@--%@",self.dataArray[indexPath.row][@"departAddr"],self.dataArray[indexPath.row][@"arrivalAddr"]];
//
//            cell.priceLabel.text = [self.dataArray[indexPath.row][@"orderActPayText"] stringValue];
//            
//            [cell showValue:self.dataArray[indexPath.row][@"priceVo"] ];
//
//            
//        }
        
        
        return cell;
    }
    
    
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return 150 * kHeight;
    }

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 200, cellHeight)];
    label.text = @"12 月";
    label.textColor = carScrollColor;
    label.font = Font(14);
    [view addSubview:label];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return cellHeight;
}


-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
   
    
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
